'use strict';

var mongoose = require('mongoose'),
	ExamType = mongoose.model('ExamType'),
	_ = require('lodash'),
	Q = require('q');
module.exports.queryExamType = function(){
	var defered = Q.defer();
	ExamType.find({},null,{sort:{typeId:1}},function(err,data){
		if(err){
			defered.reject(err);
		}
		defered.resolve(data);
	});
	return defered.promise;
};
module.exports.addExamType = function(examType){
	console.log({typeId:examType.typeId});
	return ExamType.findOne({typeId:examType.typeId}).then(
		function(data){
			console.log(data);
			if( examType.type == 'add' ){
				if(!_.isEmpty(data)){
					let res = {};
					res.flag = false;
					res.info = '该ID已经存在，请修改';
					return res
				}else{
					return {flag:true};
				}
			}else{
				if(_.isEmpty(data)){
					let res = {};
					res.flag = false;
					res.info = '该类型已经被删除';
					return res
				}else{
					return {flag:true};
				}
			}
		},
		function(err){
			let res = {};
			res.flag = false;
			res.info = '查询ID出错，'+err;
			console.error(err);
			return res;
		}
	).then(
		function(data){
			console.log(data);
			if(!data.flag){
				return data;
			}else{
				return ExamType.findOneAndUpdate({typeId:examType.typeId},examType,{upsert:true,new:true}).then(
					function(data){
						return {flag:true,res:data};
					},function(err){
						console.error(err);
						let res = {};
						res.flag = false;
						res.info = '插入数据失败'+err;
						return res;
					}
				);
			}
		},function(err){
			console.error(err);
			let res = {};
			res.flag = false;
			res.info = '查询ID出错，'+err;
			return res;
		}
	);
	// ExamType.findOneAndUpdate({id:examType.id},examType,{upsert:true,new:true},function(err,examType){
	// 	if(err){
	// 		defered.reject(err);
	// 	}
	// 	defered.resolve(examType);
	// });
	// return defered.promise;
};